﻿using Newtonsoft.Json;
using QWManage.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace QWManage.API.BlockedUsersCustom
{
    internal class BlockedUsersCustomAPI
    {
        private static Random RANDOM = new Random();
        public static List<BlockedInfo> Invoke(string cookies, ToolStripLabel tlblStatus)
        {
            List<BlockedInfo> blockedUsers = new List<BlockedInfo>();
            string url = "https://work.weixin.qq.com/wework_admin/groupchat/blockedCustomers?lang=zh_CN" +
                "&ajax=1" +
                "&f=json&pageSize=2000" +
                "&random=" + RANDOM.Next(11111, 99999);

            string json = GetHtmlSource(url, cookies);//&last_page_max_id=7306407955172010986
            Root root = JsonConvert.DeserializeObject<Root>(json);
            blockedUsers.AddRange(GetBlockedUserInfos(root));
            tlblStatus.Text = $"已采集 {blockedUsers.Count} 条黑名单记录";
            Application.DoEvents();
            while (root != null && root.data != null && !root.data.is_end)
            {
                string api = $"https://work.weixin.qq.com/wework_admin/groupchat/blockedCustomers?lang=zh_CN" +
                    $"&ajax=1" +
                    $"&f=json" +
                    $"&pageSize=2000" +
                    $"&last_page_max_id={root.data.last_page_max_id}" +
                    $"&create_time={root.data.create_time}" +
                    $"&random=" + RANDOM.Next(11111, 99999);

                json = GetHtmlSource(api, cookies);//&last_page_max_id=7306407955172010986
                root = JsonConvert.DeserializeObject<Root>(json);
                blockedUsers.AddRange(GetBlockedUserInfos(root));
                tlblStatus.Text = $"已采集 {blockedUsers.Count} 条黑名单记录";
                Application.DoEvents();
            }
            return blockedUsers;
        }
        private static List<BlockedInfo> GetBlockedUserInfos(Root root)
        {
            List<BlockedInfo> blockedUsers = new List<BlockedInfo>();
            if (root != null && root.data != null && root.data.blockedCustomers != null)
            {
                foreach (BlockedCustomers customer in root.data.blockedCustomers)
                {
                    BlockedInfo blockedUser = new BlockedInfo()
                    {
                        SID = customer.shared_person_vid,
                        SName = customer.shared_person_name,
                        STime = GetDateTime(customer.shared_date_timestamp),
                        UID = customer.id,
                        Name = customer.wx_name,
                        Avatar = customer.wx_avatar_url
                    };
                    blockedUsers.Add(blockedUser);
                }
            }
            return blockedUsers;
        }
        private static string GetHtmlSource(string url, string cookies)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Referer = "https://work.weixin.qq.com/wework_admin/frame";
            if (!string.IsNullOrEmpty(cookies))
                request.Headers.Add("Cookie", cookies);

            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            string html = php.ReadToEnd();
            return html;
        }

        public static DateTime GetDateTime(long timestamp)
        {
            //DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 
            //使用上面的方式会显示TimeZone已过时
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }
    }



    #region JSON
    public class BlockedCustomers
    {
        /// <summary>
        /// 
        /// </summary>
        public string id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string wx_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string shared_person_vid { get; set; }
        /// <summary>
        /// 花儿助理【售后找我】小琴
        /// </summary>
        public string shared_person_name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int shared_date_timestamp { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string wx_avatar_url { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int gender { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public bool is_wx_user { get; set; }
    }

    public class Data
    {
        /// <summary>
        /// 
        /// </summary>
        public List<BlockedCustomers> blockedCustomers { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string last_page_max_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public bool is_end { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string create_time { get; set; }
    }

    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public Data data { get; set; }
    }
    #endregion
}
